<?php

/**
 * Name: 签到控制器
 * User: Silent
 * Date: 2025-11-07
 * Time: 16:30:00
 */

namespace App\Http\Controllers\V1\Resources\Checkin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Checkin\CheckinRequest;
use App\Services\Checkin\CheckinService;
use Illuminate\Http\Request;
use Exception;

class CheckinController extends Controller
{
    protected $checkinService;

    public function __construct(CheckinService $checkinService)
    {
        $this->checkinService = $checkinService;
    }

    /**
     * 提交签到
     * POST /api/v1/checkin/submit
     */
    public function submit(CheckinRequest $request)
    {
        try {
            $employee = $request->input('current_user');
            // 使用 getProcessedData() 获取处理后的数据，确保布尔值被正确转换
            $signData = $request->getProcessedData();

            $result = $this->checkinService->submitSignIn($employee, $signData);

            if ($result['success']) {
                return $this->_success($result['message'], $result['data']);
            } else {
                return $this->_error($result['message']);
            }

        } catch (Exception $e) {
            return $this->_error('签到失败：' . $e->getMessage());
        }
    }

    /**
     * 获取签到日历
     * GET /api/v1/checkin/calendar
     */
    public function calendar(Request $request)
    {
        try {
            $employee = $request->input('current_user');
            $year = $request->input('year', date('Y'));
            $month = $request->input('month', date('n'));

            // 验证年月参数
            if (!is_numeric($year) || !is_numeric($month) ||
                $year < 2020 || $year > 2030 ||
                $month < 1 || $month > 12) {
                return $this->_error('无效的年月参数');
            }

            $result = $this->checkinService->getSignInCalendar($employee, $year, $month);

            if ($result['success']) {
                return $this->_success('获取成功', $result['data']);
            } else {
                return $this->_error($result['message']);
            }

        } catch (Exception $e) {
            return $this->_error('获取日历失败：' . $e->getMessage());
        }
    }

    /**
     * 获取签到详情
     * GET /api/v1/checkin/detail/{date}
     */
    public function detail(Request $request, $date)
    {
        try {
            $employee = $request->input('current_user');

            // 验证日期格式
            if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
                return $this->_error('无效的日期格式');
            }

            $result = $this->checkinService->getSignInDetail($employee, $date);

            if ($result['success']) {
                return $this->_success('获取成功', $result['data']);
            } else {
                return $this->_error($result['message']);
            }

        } catch (Exception $e) {
            return $this->_error('获取详情失败：' . $e->getMessage());
        }
    }

    /**
     * 获取签到记录列表
     * GET /api/v1/checkin/records
     */
    public function records(Request $request)
    {
        try {
            $employee = $request->input('current_user');
            $perPage = $request->input('per_page', 15);

            // 根据用户角色获取相应的记录
            $userRole = $this->getUserRole($employee);

            if ($userRole === 'supervisor') {
                // 主管可以查看所有记录
                $teamName = $request->input('team_name');
                $filters = $this->buildFilters($request);

                // 这里需要实现获取所有班组记录的逻辑
                return $this->_success('获取成功', [
                    'message' => '主管记录查看功能待完善'
                ]);
            } else {
                // 员工和班长查看自己相关的记录
                // 这里需要根据具体需求实现
                return $this->_success('获取成功', [
                    'message' => '个人记录查看功能待完善'
                ]);
            }

        } catch (Exception $e) {
            return $this->_error('获取记录失败：' . $e->getMessage());
        }
    }

    /**
     * 获取今日签到状态
     * GET /api/v1/checkin/today-status
     */
    public function todayStatus(Request $request)
    {
        try {
            $employee = $request->input('current_user');
            $today = today()->format('Y-m-d');

            $result = $this->checkinService->getSignInDetail($employee, $today);

            if ($result['success']) {
                $data = $result['data'];

                // 简化返回数据，只包含基本状态信息
                $statusData = [
                    'date' => $today,
                    'has_signed' => isset($data['sign_record']),
                    'sign_status' => $data['sign_record']->status ?? null,
                    'sign_time' => $data['sign_record']->sign_time ?? null,
                    'can_sign' => !isset($data['sign_record']),
                ];

                return $this->_success('获取成功', $statusData);
            } else {
                // 如果没有签到记录，返回可以签到的状态
                return $this->_success('获取成功', [
                    'date' => $today,
                    'has_signed' => false,
                    'sign_status' => null,
                    'sign_time' => null,
                    'can_sign' => true,
                ]);
            }

        } catch (Exception $e) {
            return $this->_error('获取状态失败：' . $e->getMessage());
        }
    }

    /**
     * 获取打卡记录列表
     * GET /api/v1/checkin/list?page=1&limit=20&month=2025-11&status=abnormal
     */
    public function list(Request $request)
    {
        try {
            $employee = $request->input('current_user');
            
            // 获取查询参数
            $params = [
                'page' => $request->input('page', 1),
                'limit' => $request->input('limit', 20),
                'month' => $request->input('month'),
                'status' => $request->input('status')
            ];

            // 验证参数
            if ($params['page'] < 1) {
                return $this->_error('页码参数无效');
            }

            if ($params['limit'] < 1 || $params['limit'] > 100) {
                return $this->_error('每页条数参数无效，范围：1-100');
            }

            // 验证月份格式
            if ($params['month'] && !preg_match('/^\d{4}-\d{2}$/', $params['month'])) {
                return $this->_error('月份格式无效，请使用YYYY-MM格式');
            }

            // 验证状态参数
            if ($params['status'] && !in_array($params['status'], ['normal', 'abnormal'])) {
                return $this->_error('状态参数无效，支持的值：normal, abnormal');
            }

            $result = $this->checkinService->getSignInList($employee, $params);
            if ($result['success']) {
                return $this->_success('获取成功', $result['data']);
            } else {
                return $this->_error($result['message']);
            }

        } catch (Exception $e) {
            return $this->_error('获取记录列表失败：' . $e->getMessage());
        }
    }

    /**
     * 检查指定日期签到状态
     * GET /api/v1/checkin/check
     */
    public function check(Request $request)
    {
        try {
            $employee = $request->input('current_user');
            $date = $request->input('date');

            // 验证日期参数
            if (empty($date)) {
                return $this->_error('date参数不能为空');
            }

            // 验证日期格式
            if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
                return $this->_error('无效的日期格式，请使用YYYY-MM-DD');
            }

            $result = $this->checkinService->checkSignInStatus($employee, $date);

            if ($result['success']) {
                return $this->_success('获取成功', $result['data']);
            } else {
                return $this->_error($result['message']);
            }

        } catch (Exception $e) {
            return $this->_error('检查签到状态失败：' . $e->getMessage());
        }
    }

    /**
     * 获取用户角色
     */
    private function getUserRole($employee)
    {
        $position = $employee->position;

        if (in_array($position, ['主管', '部长', '经理'])) {
            return 'supervisor';
        } elseif (in_array($position, ['班长', '组长'])) {
            return 'leader';
        } else {
            // 副班长及其他职位都是普通员工权限
            return 'employee';
        }
    }

    /**
     * 构建筛选条件
     */
    private function buildFilters($request)
    {
        $filters = [];

        if ($request->has('start_date')) {
            $filters['start_date'] = $request->input('start_date');
        }

        if ($request->has('end_date')) {
            $filters['end_date'] = $request->input('end_date');
        }

        if ($request->has('status')) {
            $filters['status'] = $request->input('status');
        }

        if ($request->has('team_name')) {
            $filters['team_name'] = $request->input('team_name');
        }

        return $filters;
    }
}

